import axios from "axios";
import mconfig from "./config"
import {Message} from "element-ui"
import router from "../router"
axios.defaults.baseURL = mconfig.hosts;
axios.defaults.headers["Content-Type"] = "application/json";
axios.interceptors.request.use(
    function(config) {
        let token = JSON.parse(sessionStorage.getItem("token"));
        token && (config.headers.cnm = token);
        return config;
    },
    function(err) {
        //console.error(err);
    }
);
axios.interceptors.response.use(function(res){
    if(res.status==200){
        switch(res.data.code){
            case 200:
                return res;
                break;
            case 300:
                Message({
                    type:"error",
                    message:res.data.message?res.data.message:res.data.msg
                })
                break;
            case 500:
                Message({
                    type:"error",
                    message:res.data.message?res.data.message:res.data.msg
                })
                break;
            case 400:
                Message({
                    type:"error",
                    message:"请完整填写表单"
                })
                break;
            case 401:
                Message({
                    type:"error",
                    message:res.data.message?res.data.message:res.data.msg
                })
                sessionStorage.removeItem("token");
                sessionStorage.removeItem("store");
                router.push("/login")
                break;
            case 403:
                Message({
                    type:"error",
                    message:res.data.message?res.data.message:res.data.msg
                })
                break;
            case 406:
                Message({
                    type:"error",
                    message:res.data.message?res.data.message:res.data.msg
                })
                break;
        }
        return Promise.reject(res)
    }else
    {
    }
    return res
},error=>{
    Message({
        type:"error",
        message:"网络出现波动,请稍后重试"
    })
    return Promise.reject(error)
})
export default axios;